<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../classes/KeywordManager.php';

try {
    // 获取POST数据
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    
    if (!$data || !isset($data['keywords']) || !is_array($data['keywords'])) {
        throw new Exception('无效的请求数据');
    }
    
    $keywordManager = new KeywordManager();
    
    // 过滤空关键词
    $keywords = array_filter($data['keywords'], function($keyword) {
        return !empty(trim($keyword));
    });
    
    if (empty($keywords)) {
        echo json_encode([
            'success' => true,
            'count' => 0,
            'message' => '没有有效的关键词需要保存'
        ]);
        exit;
    }
    
    // 批量保存关联关键词
    $keywordManager->insertRelatedKeywords($keywords);
    
    echo json_encode([
        'success' => true,
        'count' => count($keywords),
        'message' => '关联关键词保存成功'
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
